import 'dart:ui';

import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import '../public.dart';

/// 我的页面
class HistoryPage extends StatefulWidget {
  HistoryPage({Key key}) : super(key: key);

  @override
  _HistoryPageState createState() {
    return _HistoryPageState();
  }
}

class _HistoryPageState extends State<HistoryPage> {
  bool isCheckedAll = false;
  bool isEdit = false;
  UserProvider user;
  UserRecordProvider userRecord;
  ThemeProvider theme;
  List<int> comicIds;

  @override
  void initState() {
    super.initState();
    providerHanddle();
  }

  void providerHanddle() {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await userRecord.setUserRecord();
      comicIds = _getComicIds();
    });
  }

  @override
  Widget build(BuildContext context) {
    // 使用Provider
    user = Provider.of<UserProvider>(context);
    userRecord = Provider.of<UserRecordProvider>(context);
    theme = Provider.of<ThemeProvider>(context);
    int len = userRecord.userRead.length ?? 0;
    return Scaffold(
        backgroundColor: theme.primaryColor,
        appBar: AppBar(
          title: Text('阅读历史'),
          leadingWidth: 44,
          leading: BackComponent(),
          backgroundColor: theme.primaryColor,
          centerTitle: true,
          actions: <Widget>[
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                if (len > 0) _toastDeleteTips();
              },
              child: Container(
                padding: EdgeInsets.only(right: 16, left: 8),
                alignment: Alignment.center,
                child: Text('清空'),
              ),
            )
          ],
        ),
        body: Column(children: [
          // Container(
          //     height: 56,
          //     padding: EdgeInsets.only(left: 16),
          //     color: ColorUtil.rgba(40, 40, 56, 1),
          //     child: Row(
          //       mainAxisAlignment: MainAxisAlignment.spaceAround,
          //       children: [
          //         Row(
          //           children: [
          //             Text(
          //               '开启App推送，不错过漫画精彩更新',
          //               style: TextStyle(
          //                   fontSize: 14,
          //                   color: ColorUtil.rgba(255, 255, 255, 0.6)),
          //             ),
          //             SizedBox(
          //               width: 10,
          //             ),
          //             FlatButton(
          //                 shape: RoundedRectangleBorder(
          //                     side: BorderSide.none,
          //                     borderRadius:
          //                         BorderRadius.all(Radius.circular(14))),
          //                 padding: EdgeInsets.only(left: 12, right: 12),
          //                 color: ColorUtil.rgba(255, 255, 255, 0.05),
          //                 minWidth: 28,
          //                 height: 28,
          //                 child: Text(
          //                   '去打开',
          //                   style: TextStyle(
          //                       fontSize: 14,
          //                       color: ColorUtil.rgba(255, 255, 255, 0.6)),
          //                 ),
          //                 onPressed: () {
          //                   print('去打开');
          //                 })
          //           ],
          //         ),
          //         FlatButton(
          //             padding: EdgeInsets.all(0),
          //             minWidth: 20,
          //             height: 20,
          //             color: ColorUtil.rgba(255, 255, 255, 0.05),
          //             child: SVG.icon('close',
          //                 size: 10, color: ColorUtil.rgba(255, 255, 255, 0.2)),
          //             shape: RoundedRectangleBorder(
          //                 side: BorderSide.none,
          //                 borderRadius: BorderRadius.all(Radius.circular(10))),
          //             onPressed: () {
          //               print('close');
          //             })
          //       ],
          //     )),
          Container(
              height: 32,
              alignment: Alignment.center,
              child: Text(
                '仅保留最近50条的阅读记录',
                style: TextStyle(color: ColorUtil.rgba(255, 255, 255, 0.3)),
              )),
          Expanded(
              child: len > 0
                  ? ListView.builder(itemCount: len, itemBuilder: _itemBuilder)
                  : EmptyComponent(
                      widgets: [
                        FlatButton(
                          onPressed: () {
                            Routers.navigateTo(RouterPage.READ_PAGE);
                          },
                          child: Text('去推荐看看'),
                          color: ColorUtil.rgba(255, 215, 59, 1),
                          height: 28,
                          minWidth: 48,
                          padding: EdgeInsets.only(left: 20, right: 20),
                          shape: RoundedRectangleBorder(
                              side: BorderSide.none,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(24))),
                        )
                      ],
                    ))
        ]));
  }

  _deleteUserRead() {
    Navigator.of(context).pop();
    UserService.deleteUserRead({
      'myuid': user.data.uid,
    }).then((res) {
      userRecord.deleteUserRead().then((res) {
        ACGN.toast.message('删除成功');
      });
    }).catchError((err) {
      print(err);
    });
  }

  void _toastDeleteTips() {
    ACGN.toast.dialog(context,
        barrierDismissible: false,
        constraints: BoxConstraints(maxWidth: 280),
        actions: [
          FlatButton(
            color: Colors.transparent,
            child: Text(
              '取消',
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          SizedBox(
            width: 1,
            height: 16,
            child: DecoratedBox(
              decoration: BoxDecoration(color: ColorUtil.rgba(18, 18, 26, 1)),
            ),
          ),
          FlatButton(
            color: Colors.transparent,
            child: Text(
              '清空',
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
            onPressed: _deleteUserRead,
          ),
        ],
        content: Center(
            child: Text(
          '确定清空全部历史记录？',
          style: TextStyle(fontSize: 16, color: Colors.white),
        )));
  }

  List<int> _getComicIds() {
    List<int> list = [];
    userRecord.userRead.forEach((item) {
      list.add(item.comicId);
    });
    return list;
  }

  Widget _itemBuilder(context, index) {
    UserReadItemModel item = userRecord.userRead[index];
    return Container(
        height: 124,
        padding: EdgeInsets.only(left: 16, right: 16, top: 12, bottom: 12),
        child: Row(children: [
          Expanded(
              child: Row(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                  width: 75,
                  margin: EdgeInsets.only(right: 10),
                  child: ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(8)),
                    child: Stack(children: [
                      AspectRatio(
                          aspectRatio: 0.75,
                          child: ImagesNetworkComponent(item.cover3x4)),
                      getIconNew(item.updateTime > item.readTime)
                    ]),
                  )),
              Expanded(
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                    Text(
                      '${item.comicName}',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(fontSize: 16, color: Colors.white),
                    ),
                    Text(
                      '读至：${item.lastChapterName}',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: 14,
                          height: 1.25,
                          color: ColorUtil.rgba(255, 255, 255, 0.6)),
                    ),
                    Text(
                      '${StringUtil.getTimeSpan(item.readTime)}',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: 14,
                          color: ColorUtil.rgba(255, 255, 255, 0.6)),
                    )
                  ]))
            ],
          )),
          FlatButton(
              padding: EdgeInsets.only(top: 5, bottom: 5, left: 12, right: 12),
              height: 28,
              minWidth: 0,
              color: ColorUtil.rgba(255, 215, 59, 1),
              shape: RoundedRectangleBorder(
                  side: BorderSide.none,
                  borderRadius: BorderRadius.all(Radius.circular(14))),
              onPressed: () {
                Routers.navigateTo(RouterPage.READ_PAGE, params: {
                  'comicId': item.comicId,
                  'chapterId': item.chapterId,
                  'comicIds': comicIds
                });
              },
              child: Text(
                '免费看',
                style: TextStyle(
                    fontSize: 14, color: ColorUtil.rgba(51, 51, 51, 1)),
              ))
        ]));
  }
}
